package com.youlai.boot.modules.distribution.controller;

import com.youlai.boot.common.result.Result;
import com.youlai.boot.modules.distribution.service.DistributionDashboardService;
import com.youlai.boot.modules.distribution.dto.response.*;
import com.youlai.boot.modules.tp.dto.query.DateRangeQuery;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 经销看板 控制器
 *
 * @author jason
 * @since 2025-01-03
 */
@Slf4j
@Tag(name = "经销看板接口")
@RestController
@RequestMapping("/api/v1/distribution/dashboard")
@RequiredArgsConstructor
@Validated
public class DistributionDashboardController {

    private final DistributionDashboardService distributionDashboardService;

    @Operation(summary = "获取实时数据")
    @GetMapping("/realtime")
    public Result<DistributionRealTimeDataVO> getRealTimeData() {
        DistributionRealTimeDataVO result = distributionDashboardService.getRealTimeData();
        return Result.success(result);
    }

    @Operation(summary = "获取概览指标")
    @GetMapping("/overview")
    public Result<DistributionOverviewMetricsVO> getOverviewMetrics(
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {

        DateRangeQuery dateRange = DateRangeQuery.builder()
                .startDate(startDate)
                .endDate(endDate)
                .build();

        DistributionOverviewMetricsVO result = distributionDashboardService.getOverviewMetrics(dateRange);
        return Result.success(result);
    }

    @Operation(summary = "获取品牌表现列表")
    @GetMapping("/brand-performance")
    public Result<BrandPerformancePageVO> getBrandPerformanceList(
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "品牌名称") @RequestParam(required = false) String brandName,
            @Parameter(description = "一级类目") @RequestParam(required = false) String firstCategory,
            @Parameter(description = "经营模式") @RequestParam(required = false) String operationMode) {

        log.info("接收到品牌表现列表请求 - startDate: {}, endDate: {}, pageNum: {}, pageSize: {}, brandName: {}, firstCategory: {}, operationMode: {}", 
            startDate, endDate, pageNum, pageSize, brandName, firstCategory, operationMode);

        BrandPerformanceQueryVO query = BrandPerformanceQueryVO.builder()
                .startDate(startDate)
                .endDate(endDate)
                .pageNum(pageNum)
                .pageSize(pageSize)
                .brandName(brandName)
                .firstCategory(firstCategory)
                .operationMode(operationMode)
                .build();

        log.info("构建查询对象: {}", query);

        BrandPerformancePageVO result = distributionDashboardService.getBrandPerformanceList(query);
        
        log.info("返回结果 - total: {}, listSize: {}", result.getTotal(), result.getList().size());
        
        return Result.success(result);
    }

    @Operation(summary = "获取品牌详细信息")
    @GetMapping("/brand-detail/{brandName}")
    public Result<BrandPerformancePageVO.BrandPerformanceDataVO> getBrandDetail(
            @Parameter(description = "品牌名称") @PathVariable String brandName,
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {

        BrandPerformanceQueryVO query = BrandPerformanceQueryVO.builder()
                .startDate(startDate)
                .endDate(endDate)
                .brandName(brandName)
                .pageNum(1)
                .pageSize(1)
                .build();

        BrandPerformancePageVO pageResult = distributionDashboardService.getBrandPerformanceList(query);
        if (pageResult.getList().isEmpty()) {
            return Result.success(null);
        }

        return Result.success(pageResult.getList().get(0));
    }

    @Operation(summary = "获取类目分析")
    @GetMapping("/category-analysis")
    public Result<CategoryAnalysisResponseVO> getCategoryAnalysis(
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @Parameter(description = "类目级别") @RequestParam(defaultValue = "1") Integer categoryLevel) {

        DateRangeQuery dateRange = DateRangeQuery.builder()
                .startDate(startDate)
                .endDate(endDate)
                .build();

        CategoryAnalysisResponseVO result = distributionDashboardService.getCategoryAnalysis(dateRange, categoryLevel);
        return Result.success(result);
    }

    @Operation(summary = "获取经营模式分析")
    @GetMapping("/operation-mode-analysis")
    public Result<OperationModeAnalysisResponseVO> getOperationModeAnalysis(
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {

        DateRangeQuery dateRange = DateRangeQuery.builder()
                .startDate(startDate)
                .endDate(endDate)
                .build();

        OperationModeAnalysisResponseVO result = distributionDashboardService.getOperationModeAnalysis(dateRange);
        return Result.success(result);
    }

    @Operation(summary = "获取品牌排行")
    @GetMapping("/brand-ranking")
    public Result<BrandRankingResponseVO> getBrandRanking(
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @Parameter(description = "排行数量限制") @RequestParam(defaultValue = "10") Integer limit) {

        DateRangeQuery dateRange = DateRangeQuery.builder()
                .startDate(startDate)
                .endDate(endDate)
                .build();

        BrandRankingResponseVO result = distributionDashboardService.getBrandRanking(dateRange, limit);
        return Result.success(result);
    }

    @Operation(summary = "获取成交金额趋势")
    @GetMapping("/amount-trend")
    public Result<TrendDataResponseVO> getAmountTrend(
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @Parameter(description = "粒度") @RequestParam(defaultValue = "day") String granularity) {

        DateRangeQuery dateRange = DateRangeQuery.builder()
                .startDate(startDate)
                .endDate(endDate)
                .build();

        TrendDataResponseVO result = distributionDashboardService.getAmountTrend(dateRange);
        return Result.success(result);
    }

    @Operation(summary = "获取品牌数量趋势")
    @GetMapping("/brand-count-trend")
    public Result<TrendDataResponseVO> getBrandCountTrend(
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @Parameter(description = "粒度") @RequestParam(defaultValue = "day") String granularity) {

        DateRangeQuery dateRange = DateRangeQuery.builder()
                .startDate(startDate)
                .endDate(endDate)
                .build();

        TrendDataResponseVO result = distributionDashboardService.getBrandCountTrend(dateRange);
        return Result.success(result);
    }

    @Operation(summary = "获取转化率趋势")
    @GetMapping("/conversion-trend")
    public Result<TrendDataResponseVO> getConversionTrend(
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @Parameter(description = "粒度") @RequestParam(defaultValue = "day") String granularity) {

        DateRangeQuery dateRange = DateRangeQuery.builder()
                .startDate(startDate)
                .endDate(endDate)
                .build();

        TrendDataResponseVO result = distributionDashboardService.getConversionTrend(dateRange);
        return Result.success(result);
    }

    @Operation(summary = "获取看板完整数据（一次性获取所有数据）")
    @GetMapping("/all")
    public Result<DistributionDashboardAllDataVO> getDashboardData(
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {

        DateRangeQuery dateRange = DateRangeQuery.builder()
                .startDate(startDate)
                .endDate(endDate)
                .build();

        DistributionDashboardAllDataVO result = distributionDashboardService.getAllData(dateRange);
        return Result.success(result);
    }

    @Operation(summary = "导出品牌表现数据")
    @PostMapping("/export/brand-performance")
    public void exportBrandPerformance(
            @RequestBody(required = false) BrandPerformanceQueryVO query,
            HttpServletResponse response
    ) {
        try {
            // 如果没有传入查询条件，使用默认值
            if (query == null) {
                query = new BrandPerformanceQueryVO();
            }
            
            log.info("接收到导出请求，参数: {}", query);
            
            distributionDashboardService.exportBrandPerformance(query, response);
        } catch (Exception e) {
            log.error("导出品牌表现数据失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try {
                response.getWriter().write("导出失败: " + e.getMessage());
            } catch (Exception ex) {
                log.error("写入错误响应失败", ex);
            }
        }
    }

    @Operation(summary = "获取品牌选项列表")
    @GetMapping("/brand-options")
    public Result<List<String>> getBrandOptions() {
        List<String> brandOptions = distributionDashboardService.getBrandOptions();
        return Result.success(brandOptions);
    }

    @Operation(summary = "获取类目选项列表")
    @GetMapping("/category-options")
    public Result<List<String>> getCategoryOptions() {
        List<String> categoryOptions = distributionDashboardService.getFirstCategoryOptions();
        return Result.success(categoryOptions);
    }

    @Operation(summary = "获取经营模式选项列表")
    @GetMapping("/operation-mode-options")
    public Result<List<String>> getOperationModeOptions() {
        List<String> operationModeOptions = distributionDashboardService.getOperationModeOptions();
        return Result.success(operationModeOptions);
    }

    @Operation(summary = "API健康检查")
    @GetMapping("/health")
    public Result<String> checkHealth() {
        return Result.success("OK");
    }

    @Operation(summary = "刷新数据")
    @PostMapping("/refresh")
    public Result<String> refreshData() {
        // 这里可以调用service的refresh方法
        return Result.success("数据刷新完成");
    }
} 